package com.hzcx.app.simplechat.util.down;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.OnProgressListener;
import com.downloader.OnStartOrResumeListener;
import com.downloader.PRDownloader;
import com.downloader.Progress;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hzcx.app.simplechat.MyApplication;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.ui.publicui.CameraActivity;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.notice.NoticeUtil;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import eason.linyuzai.download.ELoad;
import eason.linyuzai.download.listeners.MainThreadDownloadListener;
import eason.linyuzai.download.listeners.PercentProgressDownloadListener;
import eason.linyuzai.download.recycle.TaskRecycler;
import eason.linyuzai.download.task.DownloadTask;
import io.reactivex.Observable;
import okhttp3.ResponseBody;

public class DownLoadUtil {

    /**
     * 下载环信的图片到本地
     *
     * @param urls
     * @param downLoadListener
     */
    public static void downLoadImg(List<EMMessage> urls, OnDownLoadListener downLoadListener) {
        for (int i = 0; i < urls.size(); i++) {
            EMMessage message = urls.get(i);
            if (message.getType()==EMMessage.Type.CUSTOM){
                EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)||customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){

                }else {
                   continue;
                }
            }else {
                continue;
            }
            try {
                String path=null;
                EMCustomMessageBody customBody = (EMCustomMessageBody) message.getBody();
                if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_IMAGE)){
                    path = message.getStringAttribute(ChatConstant.EXTRA_IMAGE_PATH);
                }else if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){
                    path = message.getStringAttribute(ChatConstant.EXTRA_VIDEO_PATH);
                }
                if (TextUtils.isEmpty(path)){
                    ToastUtils.show("下载链接为空！");
                    return;
                }
                ELoad eload = new ELoad.Builder(MyApplication.getContext())
                        .addDownloadTaskListener(new DownloadTask.DownloadTaskListener() {
                            @Override
                            public void onDownloadTaskPrepare(DownloadTask task, Observable<ResponseBody> observable) {

                            }

                            @Override
                            public void onDownloadTaskStart(DownloadTask task) {

                            }

                            @Override
                            public void onDownloadTaskPause(DownloadTask task) {

                            }

                            @Override
                            public void onDownloadTaskResume(DownloadTask task) {

                            }

                            @Override
                            public void onDownloadTaskError(DownloadTask task, Throwable e) {
                                LogUtils.d("下载错误:" + e.getMessage());
                                downLoadListener.fail();
                            }

                            @Override
                            public void onDownloadTaskComplete(DownloadTask task) {
                                String path = task.getEntity().getFilePath() + "/" +
                                        task.getEntity().getFileName();
                                try {
                                    File file = new File(path);
                                    if (customBody.event().equals(ChatConstant.EXTRA_CUSTOM_VIDEO)){
                                        ContentValues values = new ContentValues();
                                        values.put(MediaStore.Video.Media.DATA, path);
                                        MyApplication.getContext().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
                                    }else {
                                        MediaStore.Images.Media.insertImage(MyApplication.getContext().getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                // 通知图库更新
                                MyApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "/sdcard/namecard/")));
                                LogUtils.d("下载完成：" + path);
                                downLoadListener.success(path);
                            }

                            @Override
                            public void onDownloadTaskCancel(DownloadTask task) {

                            }

                            @Override
                            public void onDownloadTaskReset(DownloadTask task) {

                            }

                            @Override
                            public void onDownloadTaskRecycle(DownloadTask task, TaskRecycler taskRecycler) {

                            }
                        }).build();
                //可以当成一个Request
                DownloadTask task = eload.url(path).filepath(CameraActivity.IMAGE_PATH).create();
                task.start();
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  下载图片
     * @param url
     * @param loadListener
     */
    public static void downLoadImg(String url,OnDownLoadListener loadListener){
        String fileName="duoChat_"+System.currentTimeMillis()+".jpg";
        PRDownloader.download(url,CameraActivity.IMAGE_PATH,
                fileName)
                .build()
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        String path=CameraActivity.IMAGE_PATH+ File.separator+fileName;
                        try {
                            File file = new File(path);
                            MediaStore.Images.Media.insertImage(MyApplication.getContext().getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 通知图库更新
                        MyApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "/sdcard/namecard/")));
                        loadListener.success(path);
                    }

                    @Override
                    public void onError(Error error) {
                        loadListener.fail();
                    }
                });
    }

    public static void downLoadVideo(String url,OnDownLoadListener loadListener){
        String fileName="duoChat_"+System.currentTimeMillis()+".mp4";
        PRDownloader.download(url,CameraActivity.IMAGE_PATH + "/",
                fileName)
                .build()
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        String path=CameraActivity.IMAGE_PATH + "/"+fileName;
                        try {
                            File file = new File(path);
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Video.Media.DATA, path);
                            MyApplication.getContext().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 通知图库更新
                        MyApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + "/sdcard/namecard/")));
                        loadListener.success(path);
                    }

                    @Override
                    public void onError(Error error) {
                        loadListener.fail();
                    }
                });
    }

    public interface OnDownLoadListener {
        void success(String path);

        void fail();
    }

    public static void downLoadNewVersion(Context context, String url) {
        PRDownloader.download(url, Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/", "duoChat.apk")
                .build()
                .setOnStartOrResumeListener(() -> {
                    LogUtils.d("开始下载");
                    NoticeUtil.createUpdateNotice(context, "下载中", "0%", 0);
                })
                .setOnProgressListener(progress -> {
                    long size = progress.totalBytes;
                    long downSize = progress.currentBytes;
                    double d = downSize * 1.0 / size;
                    int num = (int) (d * 100);
                    if(num>=99){
                        NoticeUtil.clearNotice(1);
                    }else {
                        NoticeUtil.createUpdateNotice(context, "下载中", num + "%", 1);
                    }
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        LogUtils.d("下载完成");
                        NoticeUtil.clearNotice(1);
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download/duoChat.apk";
                        AppHelper.installApk(context, path);
                    }

                    @Override
                    public void onError(Error error) {
                        LogUtils.d("下载错误：" + error.getServerErrorMessage());
                        NoticeUtil.createUpdateNotice(context, "下载失败", "下载失败", -1);
                    }
                });
    }
}
